package org.example.zpqy.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class PlantDiseaseDetectionService {
    private static final Logger logger = LoggerFactory.getLogger(PlantDiseaseDetectionService.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${local.model.api.url:http://127.0.0.1:1234/v1/chat/completions}")
    private String apiUrl;

    @Value("${local.model.name:qwen/qwen2.5-vl-7b}")
    private String modelName;

    public String callLocalModelWithImage(String imagePath) {
        try {
            String base64Image = encodeImageToBase64(imagePath);
            if (base64Image.isEmpty()) {
                logger.error("图片Base64编码失败");
                return "图片处理失败";
            }

            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(apiUrl);

            httpPost.setHeader("Content-Type", "application/json");
            // 本地模型不需要Authorization头
            // httpPost.setHeader("Authorization", "Bearer " + API_KEY);

            String jsonBody = buildRequestBodyJson(base64Image);
            StringEntity entity = new StringEntity(jsonBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            logger.info("本地模型API响应: {}", responseBody);

            return extractContent(responseBody);
        } catch (IOException e) {
            logger.error("调用本地模型失败", e);
            return "调用模型失败: " + e.getMessage();
        }
    }

    private String buildRequestBodyJson(String base64Image) {
        String imageUrl = "data:image/jpeg;base64," + base64Image;
        String prompt = "请对以下植物图片进行病虫害分析和建议，返回格式键为病虫害分析:和防治建议";

        return "{" +
                "\"model\": \"" + modelName + "\"," +
                "\"messages\": [" +
                "{" +
                "\"role\": \"user\"," +
                "\"content\": [" +
                "{" +
                "\"type\": \"text\"," +
                "\"text\": \"" + prompt + "\"" +
                "}," +
                "{" +
                "\"type\": \"image_url\"," +
                "\"image_url\": {" +
                "\"url\": \"" + imageUrl + "\"" +
                "}" +
                "}" +
                "]" +
                "}" +
                "]," +
                "\"temperature\": 0.7," +
                "\"max_tokens\": 1024" +
                "}";
    }

    private String encodeImageToBase64(String imagePath) throws IOException {
        File file = new File(imagePath);
        if (!file.exists() || !file.canRead()) {
            logger.error("图片文件不存在或无法读取: {}", imagePath);
            return "";
        }
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            byte[] imageData = new byte[(int) file.length()];
            int bytesRead = imageInFile.read(imageData);
            if (bytesRead != file.length()) {
                logger.error("图片读取不完整，预期: {} 字节，实际: {} 字节", file.length(), bytesRead);
                return "";
            }
            return Base64.getEncoder().encodeToString(imageData);
        }
    }

    private String extractContent(String jsonResult) {
        try {
            JsonNode rootNode = objectMapper.readTree(jsonResult);

            // 提取正常响应内容
            JsonNode choicesNode = rootNode.get("choices");
            if (choicesNode != null && choicesNode.isArray() && choicesNode.size() > 0) {
                JsonNode messageNode = choicesNode.get(0).get("message");
                if (messageNode != null) {
                    JsonNode contentNode = messageNode.get("content");
                    if (contentNode != null && !contentNode.asText().isEmpty()) {
                        return contentNode.asText();
                    }
                }
            }

            // 提取错误信息
            JsonNode errorNode = rootNode.get("error");
            if (errorNode != null) {
                String errorMsg = errorNode.get("message").asText("未知错误");
                logger.error("模型返回错误: {}", errorMsg);
                return "分析失败: " + errorMsg;
            }

            // 未匹配到任何内容
            logger.warn("未从响应中提取到有效数据: {}", jsonResult);
            return "无法获取分析结果，请检查图片是否清晰或尝试重新上传";
        } catch (Exception e) {
            logger.error("解析响应失败", e);
            return "解析结果失败: " + e.getMessage();
        }
    }
}